<template>
  <el-upload
    class="avatar-uploader"
    action="http://localhost:2000/treasure/uploadImg"
    :show-file-list="false"
    :on-success="handleAvatarSuccess"
    :before-upload="beforeAvatarUpload"
  >
    <img v-if="cover" :src="imageUrl||cover" class="avatar" />

    <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
  </el-upload>
</template>

<script setup>
import { inject, onMounted, ref } from "vue";
import { Plus } from "@element-plus/icons-vue";

let getUrlImage = inject("getUrlImage");
const props = defineProps({
  cover: {
    type: String,
    default: "",
  },
});
const imageUrl = ref("");
const handleAvatarSuccess = (response, uploadFile) => {
  imageUrl.value = response.data.imgPath;
  getUrlImage(imageUrl.value);
};

const beforeAvatarUpload = (rawFile) => {
  if (
    rawFile.type !== "image/jpg" &&
    rawFile.type !== "image/jpeg" &&
    rawFile.type !== "image/webp" &&
    rawFile.type !== "image/svg" &&
    rawFile.type !== "image/gif" &&
    rawFile.type !== "image/png"
  ) {
    ElMessage.error("图片必须是 jpg, png, webp, gif, svg, jpeg!");
    return false;
  } else if (rawFile.size / 1024 / 1024 > 5) {
    ElMessage.error("Avatar picture size can not exceed 2MB!");
    return false;
  }
  return true;
};
</script>

<style lang="scss" scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
.avatar-uploader .avatar {
    width: 100% !important;
    height: 100% !important;
    display: block;
}
</style>